package org.frv.wispr.business;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.*;

@Entity
@Table(name="ACCOUNTS")
public class Account {
	private long id;
	private String name;
	private boolean isContainer=true;
	private BigDecimal balance;
	private Account parent;
	private Set<Account> children = new HashSet<Account>();
    private List<AccountEntry> entries = new ArrayList<AccountEntry>();
    private User user;


    public Account() {}

	public Account(User user, String name, BigDecimal balance, Account parent) {
        this.parent = parent;
		this.name = name;
		this.balance = balance;
        this.user = user;
        if (parent != null) {
            this.accountType = parent.getAccountType();
        }
    }

    @ManyToOne(optional = false)
    @JoinColumn(name="user_id")
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @OneToMany(mappedBy = "account")
    @OrderBy("index")
    public List<AccountEntry> getEntries() {
        return entries;
    }

    public void setEntries(List<AccountEntry> entries) {
        this.entries = entries;
    }

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	
	@Column(nullable=false)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Column(nullable=false)
	public boolean isContainer() {
		return isContainer;
	}
	public void setContainer(boolean isContainer) {
		this.isContainer = isContainer;
	}
	
	public BigDecimal getBalance() {
		return balance;
	}
	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}

	@ManyToOne
	@JoinColumn(name="parent_id")
	public Account getParent() {
		return parent;
	}
	
	public void setParent(Account parent) {
		this.parent = parent;
	}
	
	@OneToMany(mappedBy = "parent")
	public Set<Account> getChildren() {
		return children;
	}
	
	public void setChildren(Set<Account> children) {
		this.children = children;
	}
	
	public String toString() {
		if (getParent() != null) {
			return parent.toString() + ":" + getName();
		} else {
			return getName();
		}
	}

    private AccountType accountType;

    @ManyToOne(optional = false)
    public AccountType getAccountType() {
        return accountType;
    }

    public void setAccountType(AccountType accountType) {
        this.accountType = accountType;
    }
}
